<?php

namespace app\mp\admin;

use app\system\admin\Admin;
use app\common\service\SkuMaterial as SkuMaterialService;
use app\common\service\Material as MaterialService;
use app\common\service\Sku as SkuService;
use think\Db;

/**
 * 产品模板数据表-方便填写数据--日薇系统需求
 */
class Template extends Admin
{
    protected $hisiModel = 'Template';//模型名称[通用添加、修改专用]
    protected $hisiValidate = 'Template';
    protected $hisiAddScene = '';//添加数据验证场景名
    protected $hisiEditScene = '';//更新数据验证场景名

    public function initialize()
    {
        parent::initialize();
    }

    public function index()
    {
        if ($this->request->isAjax()) {
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 20);
            $where = [
                ['t.type', '=', 'goods_size'],
            ];
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 20);
            $name = $this->request->param('name/s', '');
            $name != '' && $where[] = ['t.name', 'like', "%{$name}%"];
            $order = "t.order asc,t.id desc";
            $list = db('template t')
                ->field('t.*')
                ->where($where)->page($page)->limit($limit)->orderRaw($order)->select();
            $data['count'] = db('template t')
                ->field('t.*')
                ->where($where)->count();
            $data['data'] = $list;
            $data['code'] = 0;
            $data['msg'] = '';
            return json($data);
        }
        $assign = [];
        return $this->assign($assign)->fetch();
    }

    public function add()
    {
        if ($this->request->isAjax()) {
            $param = [
                'type' => 'goods_size',
                'name' => $this->request->param('name/s', ''),
                'order' => $this->request->param('order/d', 0),
                'data' => [],
                'create_time' => time(),
                'update_time' => time(),
            ];

            $sizenameData = $this->request->param('sizename/a', []);
            $measurementData = $this->request->param('measurement/a', []);
            $partData = $this->request->param('part/a', []);
            $sizeData = $this->request->param('size/a', []);
            $sizeTiaoData = $this->request->param('size_tiao/a', []);

            $skuData = [];
            $skuData['ps_part'] = json_encode($partData);
            $skuData['ps_measurement'] = json_encode($measurementData);
            $skuData['ps_size_tiao'] = json_encode($sizeTiaoData);

            if (count(array_filter($sizenameData)) != count(array_unique(array_filter($sizenameData)))) {
                throw new \Exception('尺码设置异常');
            }

            if (count(array_filter($partData)) != count(array_unique(array_filter($partData)))) {
                throw new \Exception('部位设置异常');
            }

            $psSizenameData = [];
            $psSizeData = [];
            foreach ($sizenameData as $k => $v) {
                if ($v != '') {
                    $items = arrayGet($sizeData, $k, []);
                    foreach ($items as $sv) {
                        if ($sv == '') throw new \Exception("尺码 {$v} 列有数据未填写");
                    }

                    $psSizenameData[] = $v;
                    $psSizeData[] = $items;
                } else {
                    unset($sizenameData[$k]);
                    unset($sizeData[$k]);
                }
            }
            $skuData['ps_size_name'] = json_encode($psSizenameData);
            $skuData['ps_size'] = json_encode($psSizeData);
            $param['data'] = json_encode($skuData);;
            $id = db('template')->insertGetId($param);
            return $this->Json(1, '操作成功', $id);
        }
        $formData = [];
        $assign = [
            'formData' => $formData,
            'factoryKV' => ['' => '请选择'] + getFactoryKV(true),
            'smList' => [],
            'sizeNameList' => ['' => '请选择'] + getSizeKV(),
            'partList' => ['' => '请选择'] + getPartKV(),
            'partListAll' => db('part')->select(),
            'sizenameArr' => [],
            'partArr' => [],
            'measurementArr' => [],
            'sizeArr' => [],
            'processLevel' => config('mimo.process_level'),
            'caichuangPosition' => config('mimo.caichuang_position'),
            'xm_select_data' => $this->_get_xm_select_data(),
        ];
        $template = $this->request->param('template', 'form');
        return $this->assign($assign)->fetch($template);
    }

    private function _get_xm_select_data()
    {
        $res = [];
        $list = db('size')->order('num asc,id asc')->select();
        foreach ($list as $k => $v) {
            $res[] = [
                'name' => $v['name'],
                'value' => $v['id'],
                'data-option' => $v['num'],
                'data-order' => $k,
            ];
        }
        return $res;
    }

    public function edit()
    {
        $id = $this->request->param('id/d', 0);
        if ($this->request->isAjax()) {
            $param = [
                'type' => 'goods_size',
                'name' => $this->request->param('name/s', ''),
                'order' => $this->request->param('order/d', 0),
                'data' => [],
//                'create_time' => time(),
                'update_time' => time(),
            ];

            $sizenameData = $this->request->param('sizename/a', []);
            $measurementData = $this->request->param('measurement/a', []);
            $partData = $this->request->param('part/a', []);
            $sizeData = $this->request->param('size/a', []);
            $sizeTiaoData = $this->request->param('size_tiao/a', []);

            $skuData = [];
            $skuData['ps_part'] = json_encode($partData);
            $skuData['ps_measurement'] = json_encode($measurementData);
            $skuData['ps_size_tiao'] = json_encode($sizeTiaoData);

            if (count(array_filter($sizenameData)) != count(array_unique(array_filter($sizenameData)))) {
                throw new \Exception('尺码设置异常');
            }

            if (count(array_filter($partData)) != count(array_unique(array_filter($partData)))) {
                throw new \Exception('部位设置异常');
            }

            $psSizenameData = [];
            $psSizeData = [];
            foreach ($sizenameData as $k => $v) {
                if ($v != '') {
                    $items = arrayGet($sizeData, $k, []);
                    foreach ($items as $sv) {
                        if ($sv == '') throw new \Exception("尺码 {$v} 列有数据未填写");
                    }

                    $psSizenameData[] = $v;
                    $psSizeData[] = $items;
                } else {
                    unset($sizenameData[$k]);
                    unset($sizeData[$k]);
                }
            }
            $skuData['ps_size_name'] = json_encode($psSizenameData);
            $skuData['ps_size'] = json_encode($psSizeData);
            $param['data'] = json_encode($skuData);;
            $id = db('template')->where(['id' => $id])->update($param);
            return $this->Json(1, '操作成功', $id);
        }
        $formData = db('template')->where('id', $id)->find();
        $templateData = json_decode($formData['data'], true);
        $psSizeArr = [];
        $psSize = json_decode($templateData['ps_size'], true);
        foreach ($psSize as $k => $v) {
            $psSizeArr[] = array_values($v);
        }
        $assign = [
            'formData' => $formData,
            'factoryKV' => ['' => '请选择'] + getFactoryKV(true),
            'smList' => [],
            'sizeNameList' => ['' => '请选择'] + getSizeKV(),
            'partList' => ['' => '请选择'] + getPartKV(),
            'partListAll' => db('part')->select(),
            'sizenameArr' => json_decode($templateData['ps_size_name'], true) ? array_values(json_decode($templateData['ps_size_name'], true)) : [],
            'partArr' => json_decode($templateData['ps_part'], true) ? array_values(json_decode($templateData['ps_part'], true)) : [],
            'measurementArr' => json_decode($templateData['ps_measurement'], true) ? array_values(json_decode($templateData['ps_measurement'], true)) : [],
            'sizeTiaoArr' => json_decode($templateData['ps_size_tiao'], true) ? array_values(json_decode($templateData['ps_size_tiao'], true)) : [],
            'sizeArr' => $psSizeArr,
            'processLevel' => config('mimo.process_level'),
            'caichuangPosition' => config('mimo.caichuang_position'),
            'xm_select_data' => $this->_get_xm_select_data(),
        ];
        $template = $this->request->param('template', 'form');
        return $this->assign($assign)->fetch($template);
    }

    public function selectItem()
    {
        $assign = [];
        return $this->assign($assign)->fetch();
    }

    public function getInfoHtml()
    {
        $id = $this->request->param('id/d', 0);
        $formData = db('template')->where('id', $id)->find();
        $templateData = json_decode($formData['data'], true);
        $psSizeArr = [];
        $psSize = json_decode($templateData['ps_size'], true);
        foreach ($psSize as $k => $v) {
            $psSizeArr[] = array_values($v);
        }
        $assign = [
            'formData' => $formData,
            'factoryKV' => ['' => '请选择'] + getFactoryKV(true),
            'smList' => [],
            'sizeNameList' => ['' => '请选择'] + getSizeKV(),
            'partList' => ['' => '请选择'] + getPartKV(),
            'partListAll' => db('part')->select(),
            'sizenameArr' => json_decode($templateData['ps_size_name'], true) ? array_values(json_decode($templateData['ps_size_name'], true)) : [],
            'partArr' => json_decode($templateData['ps_part'], true) ? array_values(json_decode($templateData['ps_part'], true)) : [],
            'measurementArr' => json_decode($templateData['ps_measurement'], true) ? array_values(json_decode($templateData['ps_measurement'], true)) : [],
            'sizeTiaoArr' => json_decode($templateData['ps_size_tiao'], true) ? array_values(json_decode($templateData['ps_size_tiao'], true)) : [],
            'sizeArr' => $psSizeArr,
            'processLevel' => config('mimo.process_level'),
            'caichuangPosition' => config('mimo.caichuang_position'),
        ];
        $template = $this->request->param('template', 'info_html');
        $data = $this->assign($assign)->fetch($template)->getContent();
        return $this->json(1, '', $data);
    }

    public function tiaoNumEdit()
    {
        if ($this->request->isAjax()) {
            $param = $this->request->param();
            $res = db('part')->where([['name', '=', $param['part']]])->update([
                'ext0' => serialize([
                    'xm_select_size' => $param['xm_select_size'],
                    'tiao_num' => $param['tiao_num'],
                    'selected_type' => $param['selected_type'],
                ]),
                'update_time' => time(),
            ]);
            return $this->json(1, '重置成功', $res);
        }
        $tr_num = $this->request->param('tr_num/d', 0);
        $part = $this->request->param('part/s', '');
        $tiaoInfo = [];
        if ($part != '') {
            $temp = db('part')->where([['name', '=', $part]])->find();
            if (trim($temp['ext0']) != '') {
                $tiaoInfo = unserialize($temp['ext0']);
            }
        }
        $assign = [
            'tr_num' => $tr_num,
            'part' => $part,
            'selectedData' => $this->_get_xm_select_data_all($tiaoInfo),
            'selected_type' => 2,//$tiaoInfo['selected_type'] ?? 2,
        ];
        return $this->assign($assign)->fetch();
    }

    private function _get_xm_select_data_all($tiaoInfo)
    {
        $selectedData = [
//            [
//                'xm_select_data' => [],
//                'tiao_num' => [],
//            ]
        ];
        for ($i = 0; $i < 5; $i++) {
            $tr = [];
            //1,xm_select_data设置
            $temp = $this->_get_xm_select_data();
            if (isset($tiaoInfo['xm_select_size'][$i]) && $tiaoInfo['xm_select_size'][$i] != '') {
                $dd = explode(',', $tiaoInfo['xm_select_size'][$i]);
                foreach ($temp as $k => $v) {
                    foreach ($dd as $k2 => $v2) {
                        if ($v['value'] == $v2) {
                            $temp[$k]['selected'] = true;
                        }
                    }
                }
            }
            $tr['xm_select_data'] = $temp;
            //2,跳码设置
            $tr['tiao_num'] = $tiaoInfo['tiao_num'][$i] ?? 0;
            $selectedData[] = $tr;
        }
        return $selectedData;
    }

    /**
     * 产品部位尺码信息 查询
     * @author zhuguosen 905502314@qq.com
     * @date 2022/1/12
     */
    public function allPartTiao()
    {
        $list = db('part')->select();
        $xm_select_data = $this->_get_xm_select_data();
        foreach ($list as $k => $v) {
            $list[$k]['ext0'] = unserialize($v['ext0']);
            $list[$k]['tiaoSizeContent'] = [];
            if ($list[$k]['ext0'] != false) {
                //找到最小 最大的码名  跳码
                foreach ($list[$k]['ext0']['xm_select_size'] as $k2 => $v2) {
                    if (trim($v2) != '') {
                        $temp = explode(',', $v2);
                        $temp2 = [];
                        foreach ($temp as $k3 => $v3) {
                            foreach ($xm_select_data as $k4 => $v4) {
                                if ($v4['value'] == $v3) {
                                    $temp2[intval($v4['data-order'])] = $v4;
                                    break;
                                }
                            }
                        }
                        ksort($temp2);
                        $temp3 = [];
                        foreach ($temp2 as $k3 => $v3) {
                            $temp3[] = $v3;
                        }
                        $list[$k]['tiaoSizeContent'][] = [
                            'min_name' => $temp3[0]['name'],
                            'max_name' => $temp3[count($temp3) - 1]['name'],
                            'tiao_num' => $list[$k]['ext0']['tiao_num'][$k2],
                        ];
                    }
                }
            }
        }
        return $this->json(1, '', $list);
    }
}